import React, { PureComponent, Fragment } from 'react';
import { Link } from 'dva/router';
import { connect } from 'dva';
import { Card, Form, Button, Badge, Divider, Modal, Row, Col, Input, Select } from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import UpLoadForm from '../../components/UpLoadForm/UpLoadForm';
import EditForm from '../../components/UpLoadForm/UpLoadEditMatForm';
import styles from './MatterLib.less';
import car from '../../assets/car.png';

const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['待审核', '已审核', '已驳回'];
const FormItem = Form.Item;
const CreateForm = Form.create()(UpLoadForm);
const EidtMatForm = Form.create()(EditForm);
const { Option } = Select;

@connect(({ rule, dev, loading }) => ({
  rule,
  dev,
  loading: loading.models.rule,
}))
@Form.create()
export default class MatterLib extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      selectedRows: [],
      matDetail: {},
      editVisible: false,
    };
    this.method = 'pub';
  }
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'rule/fetch',
      payload: {
        page: 1,
        pageSize: 10,
      },
    });
    dispatch({
      type: 'rule/fetchVideoCode',
      payload: {},
    });
    dispatch({
      type: 'rule/fetchMatTime',
      payload: {},
    });
    dispatch({
      type: 'dev/fetchCityCodes',
    });
    dispatch({
      type: 'dev/fetchUserCodes',
    });
  }
  onFresh = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'rule/fetch',
      payload: {},
    });
  };

  getFormValue = () => {
    const { form } = this.props;
    const postvalue = {};
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const { entries } = Object;
      for (const [key, value] of entries(fieldsValue)) {
        if (value !== null && value !== undefined) {
          postvalue[key] = value;
        }
      }
    });
    return postvalue;
  };

  handleSearch = e => {
    e.preventDefault();
    const { dispatch } = this.props;
    const postvalue = this.getFormValue();
    //console.log('values', postvalue);
    dispatch({
      type: 'rule/fetch',
      payload: postvalue,
    });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const postvalue = this.getFormValue();

    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...postvalue,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    dispatch({
      type: 'rule/fetch',
      payload: params,
    });
  };
  delMatter = () => {
    Modal.confirm({
      title: '确认删除',
      content: '确认要删掉这些素材么，删除后不可恢复?',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        const { dispatch } = this.props;
        const { selectedRows } = this.state;
        if (selectedRows.length === 0) return;
        //console.log('slectROws', selectedRows);
        dispatch({
          type: 'rule/remove',
          payload: {
            matId: selectedRows,
          },
          callback: () => {
            this.setState({
              selectedRows: [],
            });
          },
        });
      },
      onCancel() {
        //console.log('Cancel');
      },
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  edit = record => {
    this.setState({ editVisible: true, matDetail: record });
  };

  handleEditModalVisible = flag => {
    this.setState({
      editVisible: !!flag,
    });
  };

  download = (href, filename = '') => {
    const a = document.createElement('a');
    a.download = filename;
    a.href = href;
    document.body.appendChild(a);
    a.click();
    a.remove();
  };

  downloadFile = (url, filename = '') => {
    fetch(url, {
      headers: new Headers({
        Origin: location.origin,
      }),
      mode: 'cors',
    })
      .then(res => res.blob())
      .then(blob => {
        const blobUrl = window.URL.createObjectURL(blob);
        this.download(blobUrl, filename);
        window.URL.revokeObjectURL(blobUrl);
      });
  };
  render() {
    const { rule, loading, dev: { cityCodes, UserCodes } } = this.props;

    //console.log('rule VideoCode', rule.VideoCode);
    const { selectedRows, modalVisible, editVisible, matDetail } = this.state;
    const columns = [
      {
        title: '素材id',
        dataIndex: 'matId',
        sorter: true,
        render: (text, record) => <a href={record.matUrl}>{record.matId}</a>,
      },
      {
        title: '文件名',
        dataIndex: 'fileName',
      },
      {
        title: '缩略图',
        dataIndex: 'thumbnail',
        render: thumbnail => (
          <img src={thumbnail || car} className={styles.Appicon} alt="icon" size="small" />
        ),
      },
      {
        title: '审核状态',
        dataIndex: 'matAuditStatus',
        render(val) {
          return <Badge status={statusMap[val]} text={status[val]} />;
        },
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        sorter: true,
      },
      {
        title: '大小',
        dataIndex: 'matSize',
      },
      {
        title: '作者',
        dataIndex: 'author',
        sorter: true,
      },
      {
        title: '单位',
        dataIndex: 'organName',
        sorter: true,
      },
      {
        title: '操作',
        render: (text, record, index) => (
          <Fragment>
            {record.matAuditStatus !== 1 ? <a onClick={() => this.edit(record)}>编辑</a> : null}
            <Divider type="vertical" />
            <Link
              to={{
                pathname: `/matter/detail/${record.matId}`,
                record,
              }}
            >
              审核
            </Link>
            <Divider type="vertical" />
            <Link
              to={{
                pathname: `/matter/geolib/${record.matId}`,
                index,
              }}
            >
              播放规则
            </Link>
            <Divider type="vertical" />
            <a onClick={() => this.downloadFile(record.matUrl, record.fileName)}>下载</a>
          </Fragment>
        ),
      },
    ];

    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      handleEditModalVisible: this.handleEditModalVisible,
    };
    const { getFieldDecorator } = this.props.form;
    return (
      <PageHeaderLayout>
        <Card bordered={false} title="素材列表">
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>
              <Form onSubmit={this.handleSearch}>
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                  <Col span={6} md={4} sm={24}>
                    <FormItem>
                      {getFieldDecorator('fileName', {
                        rules: [{ required: false, message: '请输入素材名称!' }],
                      })(<Input placeholder="文件名称" />)}
                    </FormItem>
                  </Col>
                  <Col span={6} md={4} sm={24}>
                    <FormItem>
                      {getFieldDecorator('author', {
                        rules: [{ required: false, message: '请输入作者名称!' }],
                      })(<Input placeholder="作者名称" />)}
                    </FormItem>
                  </Col>
                  <Col span={6} md={4} sm={24}>
                    <FormItem>
                      {getFieldDecorator('organName', {
                        rules: [{ required: false, message: '请输入单位名称!' }],
                      })(<Input placeholder="单位名称" />)}
                    </FormItem>
                  </Col>
                  <Col span={6} md={3} sm={24}>
                    <FormItem>
                      {getFieldDecorator('matAuditStatus')(
                        <Select allowClear="true" placeholder="审核状态" style={{ width: '100%' }}>
                          {status.map((item, index) => (
                            <Option value={index}>{item}</Option>
                          ))}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col span={6} md={3} sm={24}>
                    <span className={styles.submitButtons}>
                      <Button
                        type="primary"
                        htmlType="submit"
                        style={{ marginRight: 20 }}
                        onClick={this.handleSearch}
                      >
                        查询
                      </Button>
                      <Button
                        style={{ marginRight: 20 }}
                        icon="plus"
                        type="primary"
                        onClick={() => this.handleModalVisible(true)}
                      >
                        添加
                      </Button>
                      <Button type="primary" style={{ marginRight: 20 }} onClick={this.delMatter}>
                        删除
                      </Button>
                      <Button type="primary" onClick={this.onFresh}>
                        刷新
                      </Button>
                    </span>
                  </Col>
                </Row>
              </Form>
            </div>
            <StandardTable
              rowKey="matId"
              selectedRows={selectedRows}
              loading={loading}
              data={rule}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <CreateForm
          {...parentMethods}
          VideoCode={rule.VideoCode}
          modalVisible={modalVisible}
          UserCodes={UserCodes}
          cityCodes={cityCodes}
          MatTime={rule.MatTime}
          dispatch={this.props.dispatch}
        />
        {editVisible ? (
          <EidtMatForm
            {...parentMethods}
            VideoCode={rule.VideoCode}
            editMmodalVisible={editVisible}
            dispatch={this.props.dispatch}
            mat={matDetail}
          />
        ) : null}
      </PageHeaderLayout>
    );
  }
}
